import { defineStore } from 'pinia'
import { computed } from 'vue'
import { leadApi } from '@/api'
import type { Lead, LeadCreate, LeadUpdate } from '@/api/types'
import { createCrudStore } from './factories/createCrudStore'

/**
 * 客户 Store
 * 使用 createCrudStore 工厂快速生成标准 CRUD 逻辑
 * 并添加自定义的业务 getters
 */
export const useLeadStore = defineStore('lead', () => {
  // 使用工厂创建基础 CRUD 逻辑
  // @ts-expect-error - leadApi type inference issue with factory pattern
  const baseCrud = createCrudStore<Lead, LeadCreate, LeadUpdate>(leadApi, {
    entityName: '客户',
    entityNamePlural: '客户列表',
  })

  // ========== 自定义 Getters ==========
  const rentLeads = computed(() =>
    baseCrud.items.value.filter(
      (lead: Lead) => lead.demand_type?.includes('rent') || lead.demand_type === 'rent_whole'
    )
  )

  const buyLeads = computed(() =>
    baseCrud.items.value.filter((lead: Lead) => lead.demand_type === 'buy')
  )

  const sellLeads = computed(() =>
    baseCrud.items.value.filter((lead: Lead) => lead.demand_type === 'sell')
  )

  const leadsWithAITags = computed(() =>
    baseCrud.items.value.filter(
      (lead: Lead) => lead.ai_tags && Object.keys(lead.ai_tags).length > 0
    )
  )

  const leadsWithTags = computed(() =>
    baseCrud.items.value.filter(
      (lead: Lead) => lead.tag_names && lead.tag_names.length > 0
    )
  )

  return {
    // 基础 CRUD（重命名以保持向后兼容）
    leads: baseCrud.items,
    currentLead: baseCrud.currentItem,
    total: baseCrud.total,
    loading: baseCrud.loading,

    // 自定义 Getters
    rentLeads,
    buyLeads,
    sellLeads,
    leadsWithAITags,
    leadsWithTags,

    // Actions（重命名以保持向后兼容）
    fetchLeads: baseCrud.fetchList,
    fetchLead: baseCrud.fetchById,
    createLead: baseCrud.create,
    updateLead: baseCrud.update,
    deleteLead: baseCrud.deleteItem,
    deleteLeads: baseCrud.deleteMany,

    // ✅ P1修复: 新增恢复和已删除列表功能
    restoreLead: baseCrud.restoreItem,
    restoreLeads: baseCrud.restoreMany,
    fetchDeletedLeads: baseCrud.fetchDeletedList,
  }
})
